import React, { Component } from 'react'
import './index.scss'
import { connect } from 'react-redux'
class Life extends Component {
    constructor(props) {
        super(props)
        this.state = {
            leftLife: 5,
            leftLifeArr: [1,2,3,4,5],
            lifeImg: require('../../assets/imgs/life.png')
        }
        // 组件接收一个onRef属性 属性值是函数 把this传出去
        if(props.onRef) {
            // 把该组件对象传出去
            props.onRef(this)
        }
    }
    add =  () => {
        const life = this.state.leftLife
        const lifeArr = this.state.leftLifeArr
        if (this.state.leftLife >= 5) return
        const leftLife = life + 1
        const leftLifeArr = [...lifeArr, lifeArr.length]
        this.setState({
            leftLife,
            leftLifeArr
        })
    }
    reduce = () => {
        const leftLife = this.state.leftLife - 1
        if (!leftLife) {
            this.props.overGame()
            return
        }
        const leftLifeArr = this.state.leftLifeArr.slice(0,leftLife)
        this.setState({
            leftLife,
            leftLifeArr
        })
    }
    render() {
        const { leftLifeArr, lifeImg } = this.state
        return (
            <div className="life-box">
                {
                    leftLifeArr.map(item => <img src={lifeImg} alt="" key={item}/>)
                }
            </div>
        )
    }
}
const mapActions = (dispatch) => {
    return {
        overGame: () => dispatch({
            type: 'over'
        })
    }
}
export default connect(null,mapActions)(Life)